<template>
<div>
    <div>
        <div class="title"><h1 >八皇后游戏</h1></div>
    </div>
    <div class="gird">
        游戏规则：在8×8格的国际象棋上摆放8个皇后，使其不能互相攻击，即任意两个皇后都不能处于同一行、同一列或同一斜线上，请问该如何摆放呢。
        <br>
        <button @click="resert">重新开始</button>
        <div class="row" v-for="(row,r_index) in girds" :key="r_index"> 
            <div class="cell" v-for="(cell,c_index) in row" :key ="cell.key" @click="select(r_index,c_index)" >
               <div v-if="cell.ok"><span style="color:black;font-size:30px">Q</span></div>
            </div>
        </div>
    </div>
</div>
</template>

<script>
const girds = new  Array(8).fill(1).map((_,r)=>{
     return  new  Array(8).fill(1).map((_,c)=>{
        return {
            key: `key-${r*8 + c}`,
            ok: false
        }
    })
})
export default {
    data(){
        return{
            girds,
            queenList:[]
        }
    },
    methods:{
        select(r,c){
            let num = -1;
            for(let i=0;i<this.queenList.length;i++){
                if(r==this.queenList[i].hang && c==this.queenList[i].lie){
                     this.girds[r][c].ok = false;
                     num = i;
                     break;
                }
            }
            if(num>-1){
                this.queenList.splice(num,1);
                return;
            }
            if(this.check(r,c)){
                this.girds[r][c].ok = true;
                this.queenList.push({"hang":r,"lie":c});
            }else{
                alert('不可以放在这里');
            }
            console.log(this.queenList)
            if(this.queenList.length == 8){
                alert('恭喜你，赢得胜利');
            }
            
        },
        check(r,c){
           for(let i=0;i<this.queenList.length;i++){
               if(r==this.queenList[i].hang || c==this.queenList[i].lie || Math.abs(r-this.queenList[i].hang)== Math.abs(c-this.queenList[i].lie)){
                   return false;
               }
           }
           return true;
        },
        resert(){
            for(let i=0;i<this.queenList.length;i++){
                 this.girds[this.queenList[i].hang][this.queenList[i].lie].ok = false;
            }
            this.queenList = [];
           
        }
    }

}

</script>
<style scoped>
.gird{
    width: 400px;
    margin: 0 auto;
}
.cell{
    width:50px;
    height: 50px;
    line-height: 50px;
    text-align: center;
    background-color:#999 ;
    float:left;
    cursor: pointer;
}
/* 对索引是2的倍数的class为cll的div指定颜色 */
.cell:nth-child(2n){
    background-color: #efefef;
}
.row{
    height: 50px;
    widows: 400px;
    display: flow-root;
}
.row:nth-child(2n) .cell:nth-child(2n){
    background-color:#999 ;
}
.row:nth-child(2n) .cell:nth-child(2n-1){
    background-color:#efefef;
}
</style>